package orbito.graphics;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.util.Iterator;
import java.util.LinkedList;

public class MessageQueue {
	
	// The list of messages in this queue.
	LinkedList<Message> messages;
	
	// At most how many messages to render.
	int maxRenderCount;
	
	// The default time-to-live for messages added with none specified.
	double defaultTime = 10;
	
	// The default color for message added with none specified.
	Color defaultColor = Color.ORANGE;
	
	public MessageQueue(int maxRenderCount) {
		this.messages = new LinkedList<Message>();
		this.maxRenderCount = maxRenderCount;
	}
	
	public void addMessage(String str) {
		addMessage(str, defaultTime);
	}
	
	public void addMessage(String str, Color c) {
		addMessage(str, c, defaultTime);
	}
	
	public void addMessage(String str, double ttl) {
		addMessage(str, defaultColor, ttl);
	}
	
	public void addMessage(String str, Color c, double ttl) {
		messages.addLast(new Message(str, c, ttl));
	}
	
	public void renderMessages(Graphics2D g, Viewport v, AffineTransform tx, double t, double dt) {
		AffineTransform tr = g.getTransform();
		int x = 0, y = 0, h = g.getFontMetrics().getHeight();

		// Translate to upper left side of viewport.
		g.translate(30, 30);
		
		int index = 0;
		for (Message message : messages) {
			if (index++ >= maxRenderCount) {
				break;
			}
			
			g.setColor(message.color);
			g.drawString(message.str, x, y += h);
		}
		
		g.setTransform(tr);
	}
	
	public void processMessages(double t, double dt) {
		Iterator<Message> iter = messages.iterator();
		while (iter.hasNext()) {
			Message message = iter.next();
			message.ttl -= dt;
			if (message.ttl < 0) {
				iter.remove();
			}
		}
	}
	
	private static class Message {
		// The message string.
		String str;
		
		// The color of the message.
		Color color;
		
		// The time-to-live for the message (how long to show the message).
		double ttl;
		
		public Message(String str, Color color, double ttl) {
			this.str = str;
			this.color = color;
			this.ttl = ttl;
		}
	}
}
